package com.molyfun.service.user;

import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.stereotype.Service;

import com.molyfun.bean.user.PhoneCaptchaBean;
import com.molyfun.core.Constants;
import com.molyfun.core.base.BaseService;
import com.molyfun.core.support.Assert;
import com.molyfun.core.support.HoUserService;
import com.molyfun.core.support.HttpCode;
import com.molyfun.core.support.MhStudentService;

import com.molyfun.core.support.mq.QueueSender;
import com.molyfun.core.support.mq.vo.Sms;
import com.molyfun.core.util.CommonUtil;
import com.molyfun.core.util.PasswordUtil;
import com.molyfun.core.util.RedisUtil;
import com.molyfun.model.student.HoUserBean;
import com.molyfun.model.student.MhStudent;
import com.molyfun.model.user.HoUser;
import com.molyfun.provider.student.MhStudentProvider;
import com.molyfun.provider.user.HoUserProvider;
import com.molyfun.web.base.UserThreadLocal;

/**
 */
@Service
public class HoUserServiceImpl extends BaseService<HoUserProvider, HoUser> implements HoUserService{
	@Autowired
	public void setProvider(HoUserProvider provider) {
		this.provider = provider;
	}


	@Autowired
	private QueueSender queueSender;
	// 线程池
	private ExecutorService executorService = Executors.newCachedThreadPool();




	//	public void updateToken(MhStudent student) {
	//		provider.update(student);
	//	}

	//获取验证啊
	public String captchaCode(String phone) {
		Assert.mobile(phone);
		HoUser user = provider.queryByPhone(phone);		
		Assert.isNull(user,"该手机号已经被注册,可直接登陆");
		String key = getCaptchaKey(phone);
		PhoneCaptchaBean record = (PhoneCaptchaBean) RedisUtil.getNoRestExpire(key);
		if(record == null)
		{
			//验证码6分钟失效时间
			return createCaptchaInfo(key,phone);
		}
		else
		{
			//间隔在一分钟之内
			if (System.currentTimeMillis() - record.getCreatedatetime() < Constants.CAPTCHA_INTERVAL_TIME) 
			{
				Assert.noVaild("请求频繁,请稍后重试");
			} 
			else {
				//重新生成验证码
				//验证码6分钟失效时间
				return createCaptchaInfo(key,phone);
			}
		}
		return null;
	}

	/**
	 * 检查验证码
	 * @param code
	 * @return
	 */
	public boolean checkCaptcha(String phone,String code) {
		Assert.mobile(phone);
		String key = getCaptchaKey(phone);
		PhoneCaptchaBean record = (PhoneCaptchaBean) RedisUtil.getNoRestExpire(key);
		if(record == null)
		{
			Assert.noVaild("验证码信息不存在,请重新获取");
		}
		else
		{
			//间隔在一分钟之内
			if (System.currentTimeMillis() - record.getCreatedatetime() > Constants.CAPTCHA_EXPIRE_TIME) 
			{
				Assert.noVaild("验证码已失效,请重新获取");
			} 
		}
		if(!code.equals(record.getCaptchacode()))
		{
			return false;
		}
		return true;
	}

	/** 
	 * 用户注册
	 * @param phone
	 * @param password
	 * @param captchacode
	 */
	public void reg(String phone, String password, String captchacode) 
	{
		Assert.mobile(phone);
		//验证对应手机号用户是否存在
		HoUser user = provider.queryByPhone(phone);		
		Assert.isNull(user,"该手机号已经被注册,可直接登陆");
		//验证验证码是否正确
		if(!checkCaptcha(phone,captchacode))
		{
			Assert.noVaild("验证失败");
		}
		//生成用户名称
		String userName = checkName();
		user = new HoUser();
		user.setPhone(phone);
		user.setUsername(userName);
		//1:注册用户
		user.setUsertype((short) 1);
		user.setEmail("");
		user.setHeadimgurl("");
		user.setCreatedatetime(new Date());
		user.setSex("0");
		user.setToken("");
		// 状态1：可用,0：禁用 2：已删除
		user.setStatus((short) 1);
		password = PasswordUtil.encrypt(password, Constants.ValidStr, PasswordUtil.getStaticSalt());
		user.setPassword(password);
		provider.add(user);
	}

	/**
	 * 登陆
	 * @param userName
	 * @param password
	 * @return
	 */
	public HoUser login(HoUser user) {
		String password = PasswordUtil.encrypt(user.getPassword(), Constants.ValidStr, PasswordUtil.getStaticSalt());
		user.setPassword(password);
		user =  provider.queryUserByUserNameAndPhone(user);
		Assert.notNull(user,"用户名或密码不正确");
		return user;
	}


	private String createCaptchaInfo(String key,String phone)
	{
		String captchaCode = CommonUtil.captchaRandom(true, 4);
		PhoneCaptchaBean bean = new PhoneCaptchaBean();
		bean.setCaptchacode(captchaCode);
		bean.setCreatedatetime(System.currentTimeMillis());
		RedisUtil.set(key, bean,360);
		sendSms(new Sms(phone,"你好项目测试"));
		return captchaCode;
	}

	private void sendSms(final Sms sms) {
		executorService.submit(new Runnable() {
			public void run() {
				//			queueSender.send("molyfun.smsSender", sms);
			}
		});
	}

	/** 获取手机号验证码redis key */
	protected String getCaptchaKey(String phone) {
		StringBuilder sb = new StringBuilder(Constants.CACHE_NAMESPACE);
		sb.append(Constants.CAPTCHA_CODE);
		return sb.append(phone).toString();
	}


	private String checkName()
	{
		String name = CommonUtil.generateWord();
		HoUser user = provider.queryByName(name);
		if(user != null)
		{
			checkName();
		}
		else
		{
			return name;
		}
		return null;
	}

	//	public void updateInfo(MhStudentBean bean, String id) {
	//		MhStudent student = provider.queryById(id);
	//		Assert.notNull(bean, "USER",id);	
	//		BeanUtils.copyProperties(bean,student,MhStudentBean.class);
	////		provider.update(student);
	////		return setSuccessModelMap(modelMap);
	//	}

	/**
	 * @param bean
	 */
	public void updatePassword(HoUser user,HoUserBean bean) {
		String password = PasswordUtil.encrypt(bean.getPassword(), Constants.ValidStr, PasswordUtil.getStaticSalt());
		user.setPassword(password);	
		provider.update(user);
	}
	
	
	/**
	 * @param token
	 * @return
	 */
	public String queryUserIdByToken(String token) {
		return provider.queryUserIdByToken(token);
	}

}
